﻿using System;
using System.Windows;
using System.Windows.Controls;

namespace WPFPractice.UserControls
{
    /// <summary>
    /// 支持点击取消选中的 RadioButton;
    /// </summary>
    public partial class RadioButtonUncheck : RadioButton
    {
        /// <summary>
        /// 上次的选中状态
        /// </summary>
        private bool _lastChecked;

        /// <summary>
        /// 内容字符串
        /// </summary>
        private string ContentStr => Content + "";

        public RadioButtonUncheck()
        {
            InitializeComponent();

            Click += RadioButtonUncheck_Click; ;
            PreviewMouseDown += RadioButtonUncheck_PreviewMouseDown; ;
            Checked += RadioButtonUncheck_Checked;
            Unchecked += RadioButtonUncheck_Unchecked;
        }

        /// <summary>
        /// 点击事件处理方法
        /// </summary>
        private void RadioButtonUncheck_Click(object sender, RoutedEventArgs e)
        {
            Console.WriteLine($"[{ContentStr}]触发 Click 事件");
            //SwitchStatus();
        }

        /// <summary>
        /// 鼠标按下事件处理方法
        /// </summary>
        private void RadioButtonUncheck_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            Console.WriteLine($"[{ContentStr}]触发 PreviewMouseDown 事件");
            SwitchStatus();
            e.Handled = true;
        }

        /// <summary>
        /// 切换状态
        /// </summary>
        private void SwitchStatus()
        {
            if (_lastChecked)
            {
                IsChecked = false;
                //_lastChecked = false;
            }
            else
            {
                IsChecked = true;
                //_lastChecked = true;
            }
        }

        /// <summary>
        /// 选中事件 处理方法
        /// </summary>
        private void RadioButtonUncheck_Checked(object sender, RoutedEventArgs e)
        {
            Console.WriteLine($"[{ContentStr}]触发 Checked 事件");
            _lastChecked = true;
        }

        /// <summary>
        /// 取消选中事件 处理方法
        /// </summary>
        private void RadioButtonUncheck_Unchecked(object sender, RoutedEventArgs e)
        {
            Console.WriteLine($"[{ContentStr}]触发 Unchecked 事件");
            _lastChecked = false;
        }
    }
}
